## This file runs all the code necessary for replicating the simulation results
## appearing in Chiu and Xu (2021)

# please set path and source helper.r
setwd(rep_path)
source("helper.R")

## Part I: Packages and data -----------------------
# Load packages
require(doParallel)
require(dplyr)
require(QCA)
require(BRS)
require(ggplot2)
require(cowplot)
require(gridExtra)
require(grid)
require(kableExtra)

## Part II: Run BRS and QCA -----------------------

# Run simulation for BRS
# Takes a very long time to run. Resulting rule sets are supplied as part of
#   replication materials for convenience.
# The code in the following chunk will produce:
#   "sim_out_combined.rda", "sim_out_QCA.rda", and "performance.rda" (supplied)
# This procedure will likely take days to run on a desktop.

if (FALSE) {

  reticulate::use_condaenv("BRS_conda")  ## use this conda environment for BRS

  # Set number of cores
  numCores <- 4
  registerDoParallel(numCores)

  # Make data for simulations
  # generates two files: simData.rda, simIndices.rda
  source("sim/sim_make-data.R")

  
  # Note: simulations were divided into three files that have similar run time
  #   so that they could be run simultaneously on multiple nodes of an HPCC.
  # Requires: "simData.rda" and "simIndices.rda"
  # Produces "sim_out_combined.rda"
  source("sim/sim_pois_param.R")
  source("sim/sim_pois1-3.5.R")  # fastest to run
  source("sim/sim_pois4.R")  # takes about twice as long as sim_pois1-3.5.R
  source("sim/sim_pois6.R")  # takes about twice as long as sim_pois1-3.5.R
  source("sim/sim_combine.R")

  # Run simulation for QCA
  # Requires: "simData.rda" and "simIndices.rda"
  # Produces "sim_out_QCA.rda"
  source("sim/sim_QCA.R")

  # Calculate average parsimony and out of sample accuracy 
  # Needs files: "sim_out_combined.rda" and "sim_out_QCA.rda"
  # Produces "performance.rda"
  source("sim/sim_stats.R")
}

## Part II: Make graphs/plots -----------------------
# need file: "performance.rda"
load("sim/out/performance.rda")

# Make plots and tables in paper
source("sim/sim_plot.R")
# this file produces "figures/sim_rows.png" (Figure 3) and "figures/sim20.png" (Figure A2)

source("sim/sim_table.R")
# this file produces 
#  "tables/d5_tab.tex",  "tables/d10_tab.tex", "tables/d20_tab.tex" -> Table A2
#  "tables/p5_tab.tex", "tables/p10_tab.tex", "tables/p20_tab.tex" -> Table A3


